import feedparser
import urllib2
import urllib
from google.appengine.ext import db
from google.appengine.api import users
import sys 
reload(sys) 
sys.setdefaultencoding('utf-8') 

api_key = 'D766BE2C290AC55BB9397C7AB410A906'

class Status(db.Model):
    text = db.StringProperty(required=True)
    date = db.DateTimeProperty(auto_now_add=True)

d = feedparser.parse("http://xiao.heroku.com/sina.xml")

auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm='api.follow5.com',
                          uri='api.follow5.com',
                          user='luaer',
                          passwd='xiaoxiao')
opener = urllib2.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib2.install_opener(opener)

statuses = db.GqlQuery("SELECT * FROM Status ORDER BY date DESC LIMIT 30")

for entry in d.entries:
    not_found = True
    for status in statuses:
        if(cmp(entry.title, status.text) == 0):
            not_found = False
            break
    if(not_found):
        e = Status(text = entry.title)
        url = 'http://api.follow5.com/api/statuses/update.json?api_key=D766BE2C290AC55BB9397C7AB410A906'
        params = urllib.urlencode({'status': entry.title})
        auth_req = urllib2.Request(url, data=params)
        urllib2.urlopen(auth_req)
        e.put()
        break

# Create an OpenerDirector with support for Basic HTTP Authentication...

